package com.snail.service;

import com.snail.pojo.ChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cici
 * @description 记忆上下文
 * @date 2025/8/20 14:39
 */
@Service
public class ChatHistoryService {
    private static final String CHAT_KEY_PREFIX = "chat:session:";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void saveMessage(String sessionId, ChatMessage message) {
        String key = CHAT_KEY_PREFIX + sessionId;
        redisTemplate.opsForList().rightPush(key, message);
        redisTemplate.expire(key, Duration.ofDays(1));
    }

    public List<ChatMessage> getHistory(String sessionId) {
        String key = CHAT_KEY_PREFIX + sessionId;
        List<Object> list = redisTemplate.opsForList().range(key, 0, -1);
        List<ChatMessage> messages = list.stream().map(o -> (ChatMessage) o).toList();

        List<ChatMessage> dialogs = new ArrayList<>();
        ChatMessage currentAssistantMessage = null;

        for (ChatMessage message : messages) {
            if ("user".equals(message.getRole())) {
                // 遇到用户消息，直接加入列表
                dialogs.add(message);
                // 遇到新 user，清空当前 assistant 缓存
                currentAssistantMessage = null;
            } else if ("assistant".equals(message.getRole())) {
                if (currentAssistantMessage == null) {
                    // 第一次遇到连续的 assistant 消息，新建一条
                    currentAssistantMessage = new ChatMessage();
                    currentAssistantMessage.setRole("assistant");
                    currentAssistantMessage.setContent(message.getContent().trim());
                    currentAssistantMessage.setTime(message.getTime());
                    dialogs.add(currentAssistantMessage);
                } else {
                    // 拼接连续 assistant 消息
                    String cleanContent = message.getContent().trim().replaceAll("\\n{2,}", "\n");
                    currentAssistantMessage.setContent(currentAssistantMessage.getContent() + cleanContent);
                }
            }
        }


        return dialogs;
    }

    public String deleteHistory(String sessionId) {
        String key = CHAT_KEY_PREFIX + sessionId;
        return redisTemplate.delete(key).toString();
    }
}
